#include "widget.h"
#include "ui_widget.h"
#include <QSerialPortInfo>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    serial = new QSerialPort(this);
    serial->setPortName("COM15");
    serial->setBaudRate(115200);
    connect(serial, &QSerialPort::readyRead, this, &Widget::on_readyRead);

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Widget::on_timeout);
    time = 0;
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_connButton_clicked(bool checked)
{
    if (checked)
    {
        serial->open(QIODevice::ReadWrite);
        ui->connButton->setText("Disconnect");
        timer->start(1000);
    }
    else
    {
        serial->close();
        ui->connButton->setText("Connect");
        timer->stop();
    }
}

void Widget::on_readyRead()
{
    if (!serial->canReadLine())
    {
        return;
    }

    QString line = serial->readLine();
    QStringList list = line.split(":");
    if (list.size() == 1)
    {
        return;
    }

    if (list[0] == "t")
    {
        ui->temLabel->setText("T: " + list[1]);
    }

    if (list[0] == "h")
    {
        ui->humLabel->setText("H: " + list[1]);
    }
}

void Widget::on_ledButton_clicked(bool checked)
{
    if (checked)
    {
        serial->write("l");
        ui->ledButton->setText("Off");
    }
    else
    {
        serial->write("s");
        ui->ledButton->setText("On");
    }
}

void Widget::on_timeout(void)
{
    time++;

    if (time % 5 == 0)
    {
        serial->write("t");
    }

    if (time % 6 == 0)
    {
        serial->write("h");
    }
}

void Widget::on_pushButton_pressed()
{
    serial->write("b262");
}


void Widget::on_pushButton_released()
{
    serial->write("b0");
}

